package edu.usm.cs.roberge.workers;

import java.util.List;
import java.util.logging.Logger;

import javax.swing.SwingWorker;

import edu.usm.cs.roberge.Message;
import edu.usm.cs.roberge.NewsGroup;
import edu.usm.cs.roberge.NewsReaderImpl;
import edu.usm.cs.roberge.NewsReaderModel;
import edu.usm.cs.roberge.NewsReaderImpl.NewsReaderException;
import edu.usm.cs.roberge.views.FavoritesTableModel;

/**
 * Worker responsible for fetching the 10 most recent messages for a particular
 * {@link NewsGroup}
 * 
 * @author Dave Roberge
 */
public class FetchMessagesWorker extends SwingWorker<Void, Message> {
	
	private final NewsReaderImpl impl;
	private final NewsReaderModel dataModel;
	private final FavoritesTableModel tableModel;
	private final static Logger logger = Logger.getLogger(FetchMessagesWorker.class.getName());
	
	public FetchMessagesWorker(NewsReaderModel dataModel, NewsReaderImpl impl, FavoritesTableModel tableModel) {
		this.dataModel = dataModel;
		this.impl = impl;
		this.tableModel = tableModel;
	}

	@Override
	protected Void doInBackground() throws Exception {
		List<NewsGroup> favorites = dataModel.getFavorites();
		
		for(NewsGroup favorite : favorites) {
			if (favorite.hasAllMessages()) {
				tableModel.addMessages(favorite.getAllMessages());
				continue;
			}
			Message msg = null;
			try {
				msg = impl.getLastMessageForNewsGroup(favorite);
			} catch(NewsReaderException e) {
				logger.warning("Could not select news group:" + favorite.toString());
				throw e;
			}
	
			for(int i = 0; i < 10; i++) {
				if (impl.getMessageHeader(msg, false)) {
					favorite.addMessage(msg);
					publish(msg);
				}
				
				msg = impl.moveToPreviousMessage(favorite);
			}
		}
		return null;
	}

	@Override
	protected void process(List<Message> arg0) {
		for(Message msg: arg0) {
			tableModel.addMessage(msg);
		}
		tableModel.fireTableDataChanged();
	}
}
